<template>
  <div class="content-container">
    <el-row
      type="flex"
      justify="space-between"
      class="header-filter"
      :class="{ 'four-border-blueBg': use === 'page' }"
    >
      <div class="row-left">
        <el-select
          v-if="use === 'page'"
          v-model="listParams.status"
          class="item"
          :placeholder="$t('fleet.vehicleStatus')"
          clearable
        >
          <el-option
            v-for="item in g_options.vehicleStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-if="use === 'page'"
          v-model="listParams.useStatus"
          class="item"
          :placeholder="$t('fleet.vehicleUseStatus')"
          clearable
        >
          <el-option
            v-for="item in g_options.vehicleUseStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!-- <TextInput
          v-model="listParams.id"
          class="item"
          clearable
          :placeholder="$t('fleet.vehicleId')"
        /> -->
        <TextInput
          v-model="listParams.vehiclePlate"
          class="item"
          clearable
          :placeholder="$t('fleet.licensePlate')"
        />
        <DateTimeRange
          v-if="use === 'page'"
          v-model="timePeriod"
          class="item"
          :maxTime="g_dayjs().add(99, 'year')"
          :time-range="30"
          :picker-type="2"
          :clearable="false"
          :start-placeholder="$t('public.startTime')"
          :end-placeholder="$t('public.endTime')"
        />
        <el-button type="primary" @click="handleQuery">{{
          $t('public.search')
        }}</el-button>
        <el-button plain @click="handleReset">{{
          $t('public.reset')
        }}</el-button>
      </div>
      <div v-if="use === 'page'" class="row-right">
        <el-button type="primary" @click="handleCreate"
          >+ {{ $t('public.create') }}</el-button
        >
        <el-button @click="handleDelete">{{ $t('public.delete') }}</el-button>
      </div>
    </el-row>
    <!-- 弹框的表格空数据不知为什么不能横向滚动 -->
    <BaseTable v-show="false" />
    <div class="base-table-container">
      <BaseTable
        ref="refContentTable"
        v-loading="loading"
        :data="tableData"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <TableColumn
          v-if="type === 'selection'"
          type="selection"
          :selectable="selectable"
          width="43"
          reserve-selection
        />
        <TableColumn v-if="type === 'radio'" width="43">
          <template #default="{ row }">
            <el-radio
              v-model="tableRadioVal"
              :label="row"
              class="table-radio"
              :disabled="vehicleIds.includes(row.id)"
              @change="handleSelectionChange"
              >{{}}</el-radio
            >
          </template>
        </TableColumn>
        <!-- <TableColumn
          prop="id"
          :label="$t('fleet.vehicleId')"
          :column-width="columnWidthObj.id"
        /> -->
        <TableColumn
          prop="status"
          :label="$t('fleet.vehicleStatus')"
          :column-width="columnWidthObj.status"
        >
          <template #default="{ row }">
            <span
              class="dot-status"
              :class="
                g_options.getOptionText(
                  g_options.vehicleStatusOptions,
                  row.status,
                  '--',
                  'class'
                )
              "
              >{{
                g_options.getOptionText(
                  g_options.vehicleStatusOptions,
                  row.status,
                  '--'
                )
              }}</span
            >
          </template>
        </TableColumn>
        <TableColumn
          v-if="use === 'page'"
          prop="useStatus"
          :label="$t('fleet.vehicleUseStatus')"
          :column-width="columnWidthObj.useStatus"
        >
          <template #default="{ row }">
            <span
              class="dot-status"
              :class="
                g_options.getOptionText(
                  g_options.vehicleUseStatusOptions,
                  row.useStatus,
                  '--',
                  'class'
                )
              "
              >{{
                g_options.getOptionText(
                  g_options.vehicleUseStatusOptions,
                  row.useStatus,
                  '--'
                )
              }}</span
            >
          </template>
        </TableColumn>
        <TableColumn
          prop="vehiclePlate"
          :label="$t('fleet.licensePlate')"
          :column-width="columnWidthObj.vehiclePlate"
        />
        <TableColumn
          prop="driverName"
          :label="$t('fleet.driver')"
          :column-width="columnWidthObj.driverName"
        />
        <TableColumn
          prop="driverPhone"
          :label="$t('fleet.phone')"
          :column-width="columnWidthObj.driverPhone"
        />
        <TableColumn
          prop="seatCount"
          :label="$t('fleet.passengerCapacity')"
          :column-width="columnWidthObj.seatCount"
        />
        <TableColumn
          prop="costPerDay"
          :label="`${$t('fleet.vehicleCost')}(${$t('public.sky')})`"
          :column-width="columnWidthObj.costPerDay"
        />
        <TableColumn
          prop="costPerKm"
          :label="`${$t('fleet.vehicleCost')}(${$t('fleet.kilometer')})`"
          :column-width="columnWidthObj.costPerKm"
        />
        <TableColumn
          prop="regionCode"
          :label="$t('fleet.region')"
          :column-width="columnWidthObj.regionCode"
        >
          <template #default="{ row }">
            <span>{{ g_utils.getRegionName(row.regionCode) }}</span>
          </template>
        </TableColumn>
        <TableColumn
          prop="createTime"
          :label="$t('public.createTime')"
          :column-width="columnWidthObj.createTime"
        />
        <TableColumn
          prop="action"
          fixed="right"
          :label="$t('public.action')"
          :column-width="columnWidthObj.action"
        >
          <template #default="{ row }">
            <el-button text @click="handleViewSchedule(row)">
              {{ $t('fleet.schedule') }}
            </el-button>
            <el-button text @click="handleDetailDialog(row)">
              {{ $t('public.detail') }}
            </el-button>
            <el-button
              v-if="use === 'page'"
              text
              @click="handleEditDialog(row)"
            >
              {{ $t('public.edit') }}
            </el-button>
            <el-button
              v-if="use === 'page'"
              text
              @click="handleQrcodeView(row)"
            >
              {{ $t('fleet.createVehicleQRCode') }}
            </el-button>
          </template>
        </TableColumn>
      </BaseTable>
      <BasePagination
        v-model:page-size="pageSize"
        v-model:current-page="pageNum"
        :total="total"
        @change="getTableList()"
      />
    </div>
    <!-- 日程 -->
    <Schedule
      v-if="scheduleVisible"
      v-model="scheduleVisible"
      :vehicle-id="rowId"
      :type="addOrEditScheduleType"
    />
    <!-- 新建 -->
    <AddOrEditDialog
      v-if="addOrEditVisible"
      :id="rowId"
      v-model="addOrEditVisible"
      :type="addOrEditType"
      @update="handleQuery"
    />
    <!-- 详情 -->
    <DetailDialog v-if="detailVisible" :id="rowId" v-model="detailVisible" />
    <!-- 车辆二维码 -->
    <el-image
      ref="vehicleQrcodeRef"
      style="width: 0; height: 0"
      :src="qrCodeUrl"
      :preview-src-list="[qrCodeUrl]"
      fit="cover"
    />
  </div>
</template>

<script setup>
import QRCode from 'qrcode'
import Schedule from './Schedule.vue'
import AddOrEditDialog from './AddOrEditDialog.vue'
import DetailDialog from './DetailDialog.vue'

const props = defineProps({
  use: {
    type: String,
    default: 'page' // page-页面 | dialog-弹框
  },
  tenantId: {
    type: String,
    default: '' // 组织id
  },
  type: {
    type: String,
    default: 'selection' // selection-多选 | radio-单选
  },
  loading: {
    type: Boolean,
    default: false
  },
  data: {
    type: Array,
    default: () => []
  },
  vehicleIds: {
    type: Array,
    default: () => []
  },
  vehicleStartTime: {
    type: String,
    default: ''
  },
  vehicleEndTime: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['selection-change'])

const listParams = ref({
  vehiclePlate: '',
  status: '',
  useStatus: ''
})
const timePeriod = ref([
  g_dayjs().format('YYYY-MM-DD 00:00:00'),
  g_dayjs().format('YYYY-MM-DD 23:59:59')
])
const refContentTable = ref(null)
const loading = ref(false)
const tableData = ref([])
const columnWidthObj = ref({})
const multipleSelection = ref([])
const tableRadioVal = ref('')
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
const scheduleVisible = ref(false)
const addOrEditScheduleType = ref('add')
const addOrEditVisible = ref(false)
const addOrEditType = ref('detail')
const rowId = ref('')
const detailVisible = ref(false)
const vehicleQrcodeRef = ref(null)
const qrCodeUrl = ref('')

const getTableList = () => {
  loading.value = true
  tableData.value = []
  let urlMethod = g_api.fleet.apiVehicleList
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...listParams.value,
    startTime: timePeriod.value[0],
    endTime: timePeriod.value[1]
  }
  if (props.use === 'dialog') {
    urlMethod = g_api.fleet.apiOrderVehicleList
    params = {
      ...params,
      tenantId: props.tenantId,
      startTime: props.vehicleStartTime,
      endTime: props.vehicleEndTime
    }
  }
  urlMethod(params)
    .then(({ code, data }) => {
      if (code === '200' && data) {
        tableData.value = data.items
        total.value = data.total
        useTableColumnWidth({
          refTable: refContentTable.value
        }).getTableColumnWidth(data => {
          columnWidthObj.value = data
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  getTableList()
})

const handleQuery = () => {
  refContentTable.value.refBaseTable.clearSelection()
  multipleSelection.value = []
  pageNum.value = 1
  getTableList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    vehiclePlate: '',
    status: '',
    useStatus: ''
  })
  handleQuery()
}

const handleCreate = () => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}

const handleDelete = () => {
  if (!multipleSelection.value.length) {
    return ElMessage.warning(g_t('fleet.selectVehicle'))
  }
  g_utils
    .deleteConfirm()
    .then(() => {
      loading.value = true
      const list = multipleSelection.value.map(item => ({
        id: item.id,
        useStatus: item.useStatus
      }))
      g_api.fleet
        .apiVehicleDelete({
          vehicleList: list
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}

const handleSelectionChange = val => {
  if (props.type === 'selection') {
    multipleSelection.value = val
  }
  emit('selection-change', props.type === 'radio' ? [val] : val)
}

const selectable = row => !props.vehicleIds.includes(row.id)

const handleViewSchedule = row => {
  scheduleVisible.value = true
  rowId.value = row.id
  addOrEditScheduleType.value = props.use === 'page' ? 'add' : 'view'
}

const handleDetailDialog = row => {
  detailVisible.value = true
  rowId.value = row.id
}

const handleEditDialog = row => {
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  rowId.value = row.id
}

const handleQrcodeView = async row => {
  // loading.value = true
  // g_api.fleet
  //   .apiVehicleQrcode({
  //     tenantId: row.tenantId,
  //     vehicleId: row.id
  //   })
  //   .then(async ({ code, data }) => {
  //     if (code === '200' && data) {
  qrCodeUrl.value = await QRCode.toDataURL(
    `${window.location.origin}${window.location.pathname}#/driverOrder?tenantId=${row.tenantId}&vehicleId=${row.id}`,
    {
      width: 400
    }
  )
  vehicleQrcodeRef.value.showPreview()
  //     }
  //   })
  //   .finally(() => {
  //     loading.value = false
  //   })
}

defineExpose({
  refContentTable
})
</script>

<style lang="scss" scoped>
.table-radio :deep(.el-radio__label) {
  padding-left: 0;
}
</style>
